package com.aischool.eduorg.api;

import com.aischool.common.kit.Md5Kit;
import com.aischool.common.model.AiTeacher;
import com.aischool.common.model.SysUser;
import com.aischool.params.AiTeacherParams;
import com.aischool.routes.RouteMapping;
import com.aischool.service.AiClassService;
import com.aischool.service.AiPostService;
import com.aischool.service.AiTeacherService;
import com.aischool.service.SysUserAppService;
import com.aischool.service.SysUserRoleService;
import com.aischool.service.SysUserService;
import com.aischool.utils.AppUtil;
import com.aischool.utils.DateUtil;
import com.aischool.utils.JsonCodeEnum;
import com.aischool.utils.JsonResult;
import com.aischool.utils.RegexUtil;
import com.aischool.utils.StateEnum;
import com.aischool.utils.SysAppEnum;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

@RouteMapping(url = "/api/eduorg/teacher")
public class TeacherController extends BaseApiEduorgController {
	
	@Inject
	AiTeacherService aiTeacherService;
	@Inject
	AiPostService aiPostService;
	@Inject
	SysUserService sysUserService;
	@Inject
	SysUserAppService sysUserAppService;
	@Inject
	SysUserRoleService sysUserRoleService;
	@Inject
	AiClassService aiClassService;
	
	private final int teacher_app_id = SysAppEnum.TEACHER_APP.getId();

	public void getPage() {
		// 结果类
		JsonResult jr = new JsonResult();
		// 参数类
		AiTeacherParams params = new AiTeacherParams();
		// 获取参数
		params.setAppId(teacher_app_id); // 教师终端
		params.setOrgId(this.getAttrForInt("login_org_id"));
		params.setRoleId(getInt("roleid", 0));
		params.setPageNo(getParaToInt("pageNo", getParaToInt("pageNumber", 1))); // 兼容e参数
		params.setPageSize(getParaToInt("pageSize", AppUtil.Default_PageSize));
		params.setKeywords(getPara("keywords", ""));
		params.setState(getInt("state",StateEnum.ALL.getState()));
				
		// 获取分页
		Object pageData = aiTeacherService.getPage(params);
		
		jr.setDicKV("pageData", pageData);
		
		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	public void getOne() {
		// 结果类
		JsonResult jr = new JsonResult();
		
		int teacher_id = getInt("id", 0);
		
		int org_id = this.getAttrForInt("login_org_id");
		
		Object obj = aiPostService.getPostAll();
		if (obj != null) {
			jr.setDicKV("listpost", obj);
		}
		
		obj = aiClassService.getAll(org_id, 1);
		if (obj != null) { jr.setDicKV("listclass", obj); }
		
		obj = aiTeacherService.getOneById(teacher_id);
		if (obj != null) {
			jr.setDicKV("oneinfo", obj);
		}
		
		
		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	public void save() {

		// 结果类
		JsonResult jr = new JsonResult();
		// 参数
		int login_user_id = this.getAttrForInt("login_user_id");
		int login_org_id = this.getAttrForInt("login_org_id");
		
		int teacher_id = getInt("teacher_id", 0);

		// 执行结果
		boolean bf = false;
		
		if (StrKit.isBlank(getPara("teacher_name",""))) {
			jr.appendMsg("请输入姓名！");
		}else if (getInt("post_id",0)<=0) {
			jr.appendMsg("请选择职务！");
		}else if (!RegexUtil.isMobile(getPara("teacher_mobile",""))) {
			jr.appendMsg("请输入正确的手机号码！！");
		}else if (teacher_id <= 0 && StrKit.isBlank(getPara("user_pwd",""))) {
			jr.appendMsg("请输入登录密码！");
		}else {
			AiTeacher info = getModel(AiTeacher.class, "", true);	
			SysUser infou = new SysUser();
			
			// 密码
			String pwd1 = getPara("user_pwd","");
			if (pwd1.length()>0) {
				infou.setLoginPwd(Md5Kit.MD5For8(pwd1));
			}
			
			info.setUpdateTime(DateUtil.getTimestamp());
			
			if (teacher_id > 0) {
				int user_id = 0;
				// gei already teacher
				Record rdt1 = aiTeacherService.getOneById(teacher_id);
				if (rdt1 != null) {
					user_id = rdt1.getInt("user_id");
				}
				if (user_id <=0) {
					jr.appendMsg("用户数据错误！请联系管理员！");
				}else {
					info.setTeacherMobile(null); // the mobile can't modify
					info.removeNullValueAttrs();
					
					System.err.println(info);
					
					bf = Db.tx(() -> {
						boolean bft = info.update();; // update result
						if (bft) {
							if (pwd1.length()>0) {
								infou.setUserId(info.getUserId());
								infou.setUserState(info.getTeacherStateid()); // state sync 
								infou.removeNullValueAttrs();
								bft = infou.update();
							}
						}
						return bft;
					});
					if (bf) {
						aiTeacherService.removeCache();
						sysUserService.removeCache(user_id);
					}
				}
				
			}else {
				// 新增用户，查询手机号
				Record rdu1 = sysUserService.getUserByMobile(info.getTeacherMobile());
				if (rdu1 != null) {
					jr.appendMsg("该手机号码已注册，请更换手机号码！");
				}else {
					// 插入user
					infou.setLoginName(info.getTeacherMobile());
					infou.setUserMobile(info.getTeacherMobile());
					infou.setUserName(info.getTeacherName());
					infou.setRegTime(DateUtil.getTimestamp());
					infou.setUpdateTime(DateUtil.getTimestamp());
					infou.setUserState(1); // state sync
					infou.setIsLock(false);
					infou.removeNullValueAttrs();
					
					// 插入teacher
					info.setOrgId(login_org_id);
					info.setAddUserid(login_user_id);
					info.setAddTime(DateUtil.getTimestamp());
					info.setTeacherStateid(1); // state sync
					info.removeNullValueAttrs();
					
					bf = Db.tx(() -> {
						boolean bft = true; // 添加结果
						int user_id = 0;
						bft = infou.save();
						if (bft) {
							user_id = infou.getUserId();
							// 设置用户应用权限
							sysUserAppService.setUserApp(user_id, teacher_app_id);
							// 设置用户应用角色
							sysUserRoleService.setUserAppRole(user_id, teacher_app_id, 3);
							
							info.setUserId(user_id);
							bft = info.save();
						}
						return bft;
					});
				}
				
			}
			
		}
		
		if (bf) {
			jr.setEnum(JsonCodeEnum.Success);
		}

		renderJson(jr.Dic);
	}
	


	public void del() {
		// 结果类
		JsonResult jr = new JsonResult();
		boolean bf = false;

		int org_id = this.getAttrForInt("login_org_id");
		// 表单转换类
		int teacher_id = getParaToInt("id", 0);
		if (teacher_id > 0) {
			bf = aiTeacherService.delForOrg(org_id, teacher_id);
		}else {
			String ids = get("ids","");
			bf = aiTeacherService.delMoreForOrg(org_id, ids);
		}
		
		if (bf) {
			jr.setEnum(JsonCodeEnum.Success);
		}else {
			jr.setEnum(JsonCodeEnum.Faild);
		}
		
		renderJson(jr.Dic);
	}
}
